package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.tool.utils.Func;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareInfoDao;
import com.atguigu.gulimall.ware.entity.WareInfoEntity;
import com.atguigu.gulimall.ware.feign.MemberFeignService;
import com.atguigu.gulimall.ware.service.WareInfoService;
import com.atguigu.gulimall.ware.vo.FareVO;
import com.atguigu.gulimall.ware.vo.MemberAddressVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author 17495
 */
@Service("wareInfoService")
@AllArgsConstructor
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    private final MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String) params.get("key");

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                Wrappers.<WareInfoEntity>lambdaQuery()
                        .and(Func.isNotEmpty(key), i -> i.eq(WareInfoEntity::getId, key)
                                .or()
                                .like(WareInfoEntity::getName, key)
                                .or()
                                .like(WareInfoEntity::getAddress, key)
                                .or()
                                .like(WareInfoEntity::getAreacode, key)
                        )
        );

        return new PageUtils(page);
    }

    @Override
    public FareVO getFare(Long addrId) {
        FareVO fareVO = new FareVO();
        R r = memberFeignService.info(addrId);
        MemberAddressVO memberAddress = r.getData("memberReceiveAddress", new TypeReference<MemberAddressVO>() {
        });
        if (memberAddress != null) {
            String phone = memberAddress.getPhone();
            String substring = phone.substring(phone.length() - 1);
            BigDecimal bigDecimal = new BigDecimal(substring);
            fareVO.setAddress(memberAddress);
            fareVO.setFare(bigDecimal);
            return fareVO;
        }
        return null;
    }

}
